package com.sea.base.json.coll

import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.sea.base.ext.global.toJsonTree
import com.sea.base.json.Json
import com.sea.base.json.Json.toJson
import java.io.Serializable

/**
 * java版链式put
 */
internal class JsonMapImpl : JsonElement(), Serializable, IJsonMap {
    val map = HashMap<String?, Any?>()

    /**
     * 返回自己
     */
    override fun put(k: String, v: Any?) = this.also { map[k] = if (v is CharSequence) v.toString() else v }

    override fun get(k: String) = map[k]

    override fun containsKey(k: String) = map.containsKey(k)

    override fun toMap() = map

    override val size: Int
        get() = map.size

    override fun isJsonObject() = true

    override fun getAsJsonObject() = Json.toJsonTree(map) as JsonObject

    override fun deepCopy() = asJsonObject

    override fun toString() = toJson()

    override fun toJson() = toJson(map)

    override fun toPathParameter(): String {
        if (map.isEmpty()) {
            return ""
        }
        val builder = StringBuilder()
        for ((key, value) in map) {
            if (builder.isNotEmpty()) {
                builder.append("&")
            }
            builder.append(key).append("=").append(value)
        }
        return builder.toString()
    }
}